package com.lw.leetcode.other.b;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * 355. 设计推特
 *
 * @author liw
 * @version 1.0
 * @date 2021/12/28 21:45
 */
public class Twitter {


    private Map<Integer, Set<Integer>> map;
    private Map<Integer, List<Long>> newsMap;
    private long count;

    public Twitter() {
        map = new HashMap<>();
        newsMap = new HashMap<>();
    }

    public void postTweet(int userId, int tweetId) {
        newsMap.computeIfAbsent(userId, v -> new ArrayList<>()).add((count << 32) + tweetId);
        count++;
    }

    public List<Integer> getNewsFeed(int userId) {
        List<Integer> values = new ArrayList<>();
        List<Integer> values2 = new ArrayList<>();
        PriorityQueue<Long> queue = new PriorityQueue<>(11);
        List<Long> longs = newsMap.get(userId);
        if (longs != null) {
            int size = longs.size();
            int min = Math.min(longs.size(), 10);
            for (int i = size - min; i < size; i++) {
                queue.add(longs.get(i));
            }
        }
        find(queue, map.get(userId));
        while (!queue.isEmpty()) {
            Long poll = queue.poll();
            values.add(poll.intValue());
        }
        for (int i = values.size() - 1; i >= 0; i--) {
            values2.add(values.get(i));
        }
        return values2;
    }

    public void follow(int followerId, int followeeId) {
        map.computeIfAbsent(followerId, v -> new HashSet<>()).add(followeeId);
    }

    public void unfollow(int followerId, int followeeId) {
        if (map.containsKey(followerId)) {
            map.get(followerId).remove(followeeId);
        }
    }

    private void find(PriorityQueue<Long> queue, Set<Integer> list) {
        if (list == null) {
            return;
        }
        for (int p : list) {
            List<Long> longs = newsMap.get(p);
            if (longs == null) {
                continue;
            }
            int size = longs.size();
            int min = Math.min(longs.size(), 10);

            for (int i = size - min; i < size; i++) {
                queue.add(longs.get(i));
                if (queue.size() > 10) {
                    queue.poll();
                }
            }
        }
    }

}
